<?php

namespace App\Services\Api;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use App\Models\Region;
/**
 *
 */
class ApiService
{

    /**
     * 发送验证码
     * @param [type] $phone
     * @method sendCode
     * @author chengzhigang<1256699215@qq.com>
     */
    public function sendCode($phone){
        try{
            $code = rand(100000,999999);
            $key = createCodeKey($phone);
            Cache::put($key, $code, 300);//缓存5分钟
            return ['status'=>1,'msg'=>'发送成功','data'=>['code'=>$code]];
        }catch(\Exception $e){
            Log::info('发送验证码：'.$e->getMessage());
            return ['status'=>2,'msg'=>'服务异常','data'=>[]];
        }
    }

    /**
     * 获取Uni-app省市区数据
     * @method getUniRegion
     * @author chengzhigang<1256699215@qq.com>
     */
    public function getUniRegion(){
        try{
            $data = [];
            $thirdRegion = [];
            $region = Region::where('level','>',0)->select('id','name','level','parent_id')->orderBy('level')->orderBy('id')->get()->toArray();
            foreach($region as $val){
                if($val['level'] == 1){
                    $data[$val['id']] = ['value'=>$val['id'],'name'=>$val['name'],'children'=>[]];
                }
                if($val['level'] == 2){
                    if(isset($data[$val['parent_id']])){
                        $data[$val['parent_id']]['children'][$val['id']] = ['value'=>$val['id'],'name'=>$val['name'],'children'=>[]];
                    }
                }
                if($val['level']==3){
                    $thirdRegion[$val['parent_id']][] = ['value'=>$val['id'],'name'=>$val['name']];
                }
            }
            $data = array_values($data);
            foreach($data as $key=>$v){
                foreach($v['children'] as $k=>$vv){
                    if(isset($thirdRegion[$k])){
                        foreach($thirdRegion[$k] as $vvv){
                            $vv['children'][] = $vvv;
                        }
                    }
                    $v['children'][$k] = $vv;
                }
                $v['children'] = array_values($v['children']);
                $data[$key] = $v;
            }
            return ['status'=>1,'msg'=>'获取成功','data'=>$data];
        }catch(\Exception $e){
            Log::info('获取省市区：'.$e->getMessage());
            return ['status'=>2,'msg'=>'服务异常','data'=>[]];
        }
    }

}
